package com.dragonfly.shutter.validator;

import java.util.regex.Pattern;

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.dragonfly.shutter.beans.UserDetail;

/**
 * 用户详细信息验证器，用户验证用户提交的详细信息
 * @author 金灵杰
 *
 */
public class UserDetailValidator implements Validator {

	/**
	 * 过滤验证器验证目标类为UserDetail
	 */
	@SuppressWarnings("unchecked")
	@Override
	public boolean supports(Class clazz) {
		return UserDetail.class.equals(clazz);
	}

	/**
	 * 验证UserDetail类中字段
	 */
	@Override
	public void validate(Object obj, Errors errors) {
		UserDetail userDetail = (UserDetail)obj;
		
		//验证用户名是否为空
		if(userDetail.getUserName() == "" || userDetail.getUserName() == null)
		{
			errors.rejectValue("userName", "userName.empty", "请输入昵称以便于交流");
		}
		
		//如果用户输入了新密码，验证新密码是否符合要求
		if(userDetail.getPassword() != "" && !Pattern.matches("^(\\w){8,12}$", userDetail.getPassword()))
		{
			errors.rejectValue("password", "password.not_fit", "密码输入不符合要求（8－12位字母、数字和下划线组合）");
		}
		
		//验证年龄是否有效
		if(userDetail.getAge() != null && (userDetail.getAge() < 0 || userDetail.getAge() > 130))
		{
			errors.rejectValue("age", "age.invalid", "无效的年龄（年龄在0到130之间，如保密，请填0）");
		}
		
		//验证默认幻灯片播放速度
		if(userDetail.getSlideSpeed() <= 0 || userDetail.getSlideSpeed() > 10)
		{
			errors.rejectValue("slideSpeed", "slideSpeed.invalid", "幻灯片播放速度为1－10的整数");
		}

	}

}
